package com.hzw.saas.service.ds.service;

import com.hzw.saas.api.ds.enums.ClientTypeEnum;
import com.hzw.saas.common.config.annotation.RedisProcessLock;
import com.hzw.saas.common.config.util.RedisUtil;
import com.hzw.saas.common.util.constants.CacheConsts;
import com.hzw.saas.service.ds.model.Heartbeat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AsyncService {

    @Resource
    private HeartbeatServiceImpl heartbeatService;
    @Resource
    private OnlineLevelInfoServiceImpl onlineLevelInfoService;

    @Async
    @RedisProcessLock(lockName = "computeBatchLevel", key = "#clientType.name()")
    public void computeBatchLevel(ClientTypeEnum clientType) {
        LocalDateTime now = LocalDateTime.now();
        if (RedisUtil.hasKey(CacheConsts.KEY_DS_HEARTBEAT_INTERVAL)) {
            Integer interval = RedisUtil.get(CacheConsts.KEY_DS_HEARTBEAT_INTERVAL);
            List<Heartbeat> heartbeatList = heartbeatService.lambdaQuery()
                    .eq(Heartbeat::getClientType, clientType)
                    .eq(Heartbeat::getCheckStatus, 0)
                    .le(Heartbeat::getEndTime, now.minusSeconds(interval * 2))
                    .list()
                    .stream()
                    .peek(heartbeat -> {
                        onlineLevelInfoService.processLevel(heartbeat);
                        heartbeat.setCheckStatus(1);
                    })
                    .collect(Collectors.toList());
            heartbeatService.updateBatchById(heartbeatList);
        }
        log.info("computeBatchLevel 异步耗时:{}", Duration.between(now, LocalDateTime.now()).toMillis());
    }
}
